import pandas as pd

def calculate_llm_sea_score():
    """
    根据指定公式计算LLM-SEA综合指标，并输出统计信息。
    """
    try:
        # 1. 读取CSV文件
        print("正在读取CSV文件...")
        df_detailed = pd.read_csv('results/knn_detailed_results copy.csv')
        df_ndcg = pd.read_csv('ndcg/knn_user_ndcg_satisfaction@3.csv')
        df_diversity = pd.read_csv('diversity_results/knn_user_semantic_diversity.csv')

        # 2. 数据预处理与合并
        # df_detailed 包含多个条目，需要按 user_id 聚合语义匹配度和情感满意度
        # 假设 match_score语义匹配度 和 satisfaction情感满意度 是数值类型
        df_agg_detailed = df_detailed.groupby('user_id').agg(
            avg_semantic_match=('match_score', 'mean'),
            avg_satisfaction=('satisfaction', 'mean')
        ).reset_index()

        # 合并所有数据到一个DataFrame
        # 先合并 detailed (聚合后) 和 ndcg
        df_merged = pd.merge(df_agg_detailed, df_ndcg, on='user_id', how='inner')
        # 再合并 diversity
        df_merged = pd.merge(df_merged, df_diversity, on='user_id', how='inner')

        print(f"合并后共有 {len(df_merged)} 个用户的完整数据。")

        # 3. 计算LLM-SEA综合指标
        print("正在计算LLM-SEA综合指标...")
        df_merged['llm_sea_score'] = (
            0.4 * df_merged['ndcg@3'] +
            0.3 * df_merged['avg_semantic_match'] +
            0.2 * df_merged['avg_satisfaction'] +
            0.1 * df_merged['semantic_diversity']
        )

        # 4. 保存结果到新文件
        output_df = df_merged[['user_id', 'llm_sea_score']]
        output_file = 'llm/knn_user_llm_sea_scores.csv'
        output_df.to_csv(output_file, index=False)
        print(f"用户LLM-SEA综合指标已保存至 '{output_file}'")

        # 5. 计算并打印统计信息
        min_score = output_df['llm_sea_score'].min()
        max_score = output_df['llm_sea_score'].max()
        mean_score = output_df['llm_sea_score'].mean()

        print("\n--- LLM-SEA 综合指标统计 ---")
        print(f"最小值: {min_score:.4f}")
        print(f"最大值: {max_score:.4f}")
        print(f"平均值: {mean_score:.4f}")
        print("---------------------------")

    except FileNotFoundError as e:
        print(f"错误：找不到文件。请检查文件路径和名称是否正确。{e}")
    except KeyError as e:
        print(f"错误：列名不匹配。请检查CSV文件中的列名。{e}")
    except Exception as e:
        print(f"发生未知错误：{e}")

if __name__ == "__main__":
    calculate_llm_sea_score()
